<template>
  <div class="progress box clmcenter">
    <p class="progressbar">加载中...{{ percent }}</p>
  </div>
</template>

<script>
export default {
  name: "LoadingPage",
  data() {
    return {
      count: 0,
      percent: "",
      openid: this.$store.state.openid,
    };
  },
  mounted: function () {
    this.preload();
  },
  methods: {
    preload() {
      let chooseEat = require.context("../assets/img", false, /\.jpg|png$/);
      let indexEat = require.context(
        "../assets/img/index",
        false,
        /\.jpg|png$/
      );
      let jpEat = require.context("../assets/img/jp", false, /\.jpg|png$/);
      // 文件夹图片
      let chooseEatList = [];
      let indexEatList = [];
      let jpEatList = [];
      // 总数据
      let allList = [];
      for (let i = 0; i < chooseEat.keys().length; i++) {
        chooseEatList.push({
          id: 1,
          img: chooseEat.keys()[i].substr(2, chooseEat.keys()[i].length),
        });
      }
      for (let i = 0; i < indexEat.keys().length; i++) {
        indexEatList.push({
          id: 2,
          img: indexEat.keys()[i].substr(2, indexEat.keys()[i].length),
        });
      }
      for (let i = 0; i < jpEat.keys().length; i++) {
        jpEatList.push({
          id: 3,
          img: jpEat.keys()[i].substr(2, jpEat.keys()[i].length),
        });
      }
      allList = chooseEatList.concat(indexEatList, jpEatList);
      // 合并数据
      this.allList = allList;
      for (var b in allList) {
        var image = new Image();
        if (allList[b].id === 1) {
          image.src = require("../assets/img/" + allList[b].img);
        }
        if (allList[b].id === 2) {
          image.src = require("../assets/img/index/" + allList[b].img);
        }
        if (allList[b].id === 3) {
          image.src = require("../assets/img/jp/" + allList[b].img);
        }
        // 图片加载
        image.onload = () => {
          this.count++;
          // 计算图片加载的百分数，绑定到percent变量
          let percentNum = Math.floor((this.count / this.allList.length) * 100);
          this.percent = `${percentNum}%`;
        };
      }
    },
  },
  watch: {
    percent: function (val) {
      // console.log(val);
      if (val === '100%') {
        // 图片加载完成后
        this.$router.replace("/index");
      }
    },
  },
};
</script>
<style lang="less" scoped>
.progress {
  background: #fff;
  justify-content: center;
  p {
    font-size: 2rem;
    color: #000;
    padding-top: 1rem;
  }
}
</style>
